<template>
  <div>
    <el-dialog
      :title="!dataForm.quotaId ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" label-position="right" ref="editForm" label-width="110px" class="demo-ruleForm">
        <el-form-item label="指标名称" prop="quotaName">
          <el-input v-model="dataForm.quotaName"></el-input>
        </el-form-item>
        <el-form-item label="监控指标" prop="quotaType">
          <el-radio-group v-model="dataForm.quotaType" @change="querySubitem('')">
          <el-radio label="0">额定值</el-radio>
          <el-radio label="1">增幅值</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计量类型" prop="quotaOType" v-if="dataForm.quotaType==1">
          <el-radio-group v-model="dataForm.quotaOType" @change="changeQuotaOType()">
            <el-radio  label="1">设备</el-radio>
            <el-radio  label="2">区域</el-radio>
            <el-radio  label="3">部门</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计量对象" prop="meterCode" v-if="dataForm.quotaOType==1||dataForm.quotaType==0">
          <el-select v-model="dataForm.meterCode" multiple style="width:100%;" @change="changeMeter">
            <el-option v-for="item in deviceList" :key="item.meterCode" :label="item.meterCode+'['+item.meterName+']'" :value="item.meterCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计量对象" prop="departName" v-if="dataForm.quotaOType==3||dataForm.quotaOType==2">
          <template>
            <el-input :placeholder="tree.inputPlace"  style="width:100%"  @click.native="inputDevice()" class="filter-item"  v-model="dataForm.departName"> </el-input>
          </template>
        </el-form-item>
        <el-form-item label="采集分类" prop="collectType">
          <el-select v-model="dataForm.collectType" style="width:100%;">
            <el-option v-for="item in meterTypeParamValueList" :key="item.collectType" :label="item.collectName" :value="item.collectType">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="增幅时间" prop="quotaUnit" v-if="dataForm.quotaType==1">
          <el-radio-group v-model="dataForm.quotaUnit" @change="changeAddedVal()">
            <el-radio  label="3">天</el-radio>
            <el-radio  label="4">月</el-radio>
            <el-radio  label="5">年</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上限" prop="upVal" v-if="dataForm.quotaType==0">
          <el-input v-model="dataForm.upVal"></el-input>
        </el-form-item>
        <el-form-item label="下限" prop="downVal" v-if="dataForm.quotaType==0">
          <el-input v-model="dataForm.downVal"></el-input>
        </el-form-item>
        <el-form-item label="监控周期" prop="quotaCycle" v-if="dataForm.quotaType==0">
          <el-input v-model="dataForm.quotaCycle" class="input-with-select">
              <el-select v-model="dataForm.quotaUnit" slot="append" @change="changeQuotaUnit()" placeholder="请选择">
                <el-option label="分钟" value="1" ></el-option>
<!--                <el-option label="小时" value="2"></el-option>
                <el-option label="天"   value="3"></el-option>-->
              </el-select>
          </el-input>
        </el-form-item>
        <template v-if="dataForm.quotaType==1">
            <el-row>
              <el-table style="width: 95%;margin-left:5%;" :data="dataForm.addedValList" border  height="200" size="mini">
                <el-table-column label="时间点" align="left" prop="timePoint"></el-table-column>
                <el-table-column label="增幅值" align="left" prop="val">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.val" size="mini" style="width: 100%;" :clearable=false type="number" placeholder="请输入增幅值"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
        </template>
        <el-form-item label="备注信息" prop="notes" style="margin-top:15px">
            <el-input v-model="dataForm.notes"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择计量对象" :visible.sync="dataForm.quotaOType==2&&showTree" @close="closeDialog()">
      <el-tree
        :style="'height:'+(containerHeight-150)+'px'"
        ref="buildTree"
        highlight-current
        :show-checkbox="true"
        node-key="buildingId"
        :data="buildingList"
        :expand-on-click-node="false"
        :props="buildTreeProps"
        :check-strictly="true"
        default-expand-all
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTree = false">取 消</el-button>
        <el-button type="primary" @click="selectDepart()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择计量对象" :visible.sync="dataForm.quotaOType==3&&showTree" @close="closeDialog()">
      <el-tree
        :style="'height:'+(containerHeight-150)+'px'"
        ref="departTree"
        highlight-current
        :show-checkbox="true"
        node-key="organizationId"
        :data="orgList"
        :expand-on-click-node="false"
        :props="orgTreeProps"
        :check-strictly="true"
        default-expand-all
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTree = false">取 消</el-button>
        <el-button type="primary" @click="selectDepart()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        orgTreeProps:{
          label: "organizationName",
          children: "children"
        },
        buildTreeProps: {
          label: "buildingName",
          children: "children"
        },
        tree:{
          inputPlace:'',
          inputName:'',
        },
        currentData:[],
        showTree:false,
        buildingList:[],
        orgList:[],

        visible: false,
        oldDevice:{
          ids:[],
          name:'',
          oldQuotaOType:'',
          oldQuotaUnit:'',
        },
        dataForm: {
          quotaId: 0,
          quotaName: '',
          quotaType: '0',
          upVal: '',
          downVal: '',
          quotaCycle: '',
          quotaOType: '1',
          quotaUnit: '1',
          notes: '',
          departName:'',
          meterCode:[],
          collectType:'',
          addedValList:[]
        },
        deviceList: [],
        meterTypeParamValueList:[],
        dataRule: {
          quotaName: [
            { required: true, message: '指标名称不能为空', trigger: 'blur' }
          ],
          quotaType: [
            { required: true, message: '监控指标不能为空', trigger: 'blur' }
          ],
          upVal: [
            { required: true, message: '上限不能为空', trigger: 'blur' }
          ],
          downVal: [
            { required: true, message: '下限不能为空', trigger: 'blur' }
          ],
          quotaCycle: [
            { required: true, message: '监控周期不能为空', trigger: 'blur' }
          ],
          quotaOType: [
            { required: true, message: '监控周期单位不能为空', trigger: 'blur' }
          ],
          quotaUnit: [
            { required: true, message: '增幅值不能为空', trigger: 'blur' }
          ],
          quotaUnit: [
            { required: true, message: '监控指标不能为空', trigger: 'blur' }
          ],
          departName:[
            { required: true, message: '计量对象不能为空', trigger: 'change' }
          ],
          meterCode:[
            { required: true, message: '计量对象不能为空', trigger: 'change' }
          ],
          collectType:[
            { required: true, message: '采集分类不能为空', trigger: 'change' }
          ]
        }
      }
    },
    computed:{
      containerHeight() {
        return Util.getClientHeight() - 253;
      },
    },
    created(){
      this.getBuildInfoList();
      this.getDepartList();
      this.getDeviceDataList();
      this.changeAddedVal();
      this.querySubitem('');
    },
    watch:{
      // "dataForm.quotaOType":function(newVal,oldVal){
      //   this.dataForm.meterCode = [];
      //   this.dataForm.departName="";
      // }
    },
    methods: {
      init (id) {
        this.dataForm.quotaId = id || 0
        this.visible = true
        this.dataForm.quotaUnit = '1'
        this.$nextTick(() => {
          this.$refs['editForm'].resetFields()
          if (this.dataForm.quotaId) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsquotainfo/info/${this.dataForm.quotaId}`),
              method: 'get',
              params: this.$http.adornParams(),
              customerId: this.$util.cookies.get("customer_id"),
              projectid:this.$util.cookies.get("cuuren_projectId")
            }).then((data) => {
              if (data && data.code === 0) {
                this.dataForm.quotaName = data.ecsquotainfo.quotaName;
                this.dataForm.quotaType = data.ecsquotainfo.quotaType;
                this.dataForm.upVal = data.ecsquotainfo.upVal;
                this.dataForm.downVal = data.ecsquotainfo.downVal;
                this.dataForm.quotaCycle = data.ecsquotainfo.quotaCycle;
                this.dataForm.quotaOType = data.ecsquotainfo.quotaOType;
                this.oldDevice.oldQuotaOType = data.ecsquotainfo.quotaOType;
             //   this.dataForm.addedVal = data.ecsquotainfo.addedVal;
                this.dataForm.quotaUnit = data.ecsquotainfo.quotaUnit;
                this.oldDevice.oldQuotaUnit = data.ecsquotainfo.quotaUnit;
                this.dataForm.notes = data.ecsquotainfo.notes;
                this.dataForm.collectType = data.ObjList[0].collectType;
                this.dataForm.meterCode = [];
                this.dataForm.addedValList = data.timeVals
                this.dataForm.departName="";
                if(this.dataForm.quotaType!=""&&this.dataForm.quotaType==0){
                  if(data.ObjList&&data.ObjList.length>0){
                    data.ObjList.forEach(element=>{
                       this.dataForm.meterCode.push(element.meterCode);
                    })
                  }
                }else if(this.dataForm.quotaType!=""&&this.dataForm.quotaType==1){
                  if(data.ObjList&&data.ObjList.length>0){
                    data.ObjList.forEach((element,index)=>{
                      if(this.dataForm.quotaOType==1){
                        this.dataForm.meterCode.push(element.meterCode);
                      }else if(this.dataForm.quotaOType==2){
                        this.dataForm.meterCode.push(element.buildingId);
                        this.dataForm.departName+=element.buildingName;
                        if(index<data.ObjList.length-1){
                          this.dataForm.departName+=",";
                        }
                      }
                      else if(this.dataForm.quotaOType==3){
                        this.dataForm.meterCode.push(element.orgId);
                        this.dataForm.departName+=element.organizationName;
                        if(index<data.ObjList.length-1){
                          this.dataForm.departName+=",";
                        }
                      }
                    })
                  }
                }
                this.querySubitem('')
                this.oldDevice.ids = JSON.parse(JSON.stringify(this.dataForm.meterCode));
                this.oldDevice.name = this.dataForm.departName;
              }

            })
          }
          else{
            this.dataForm.meterCode = [];
            this.dataForm.departName="";
            this.oldDevice.ids=[];
            this.oldDevice.name="";
            this.oldDevice.oldQuotaOType="";
            this.oldQuotaUnit='';
          }
        })
      },
      // 获取区域树
      getBuildInfoList() {
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
          method: "get",
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000,
            'key': '',
            customerId: this.$util.cookies.get("customer_id"),
            projectid:this.$util.cookies.get("cuuren_projectId")
          })
        }).then((data) => {
          if (data && data.code === 0) {
            if(data.menuList&&data.menuList.length>0){
              data.menuList.forEach(ele=>{
                if(ele.buildingId==-1){
                  ele.disabled = true;
                }
              })
            }
            this.buildingList = Util.treeDataTranslate(data.menuList,"buildingId","parentBuildingId");
          } else {
            this.buildingList = [];
          }
        });
      },
      // 获取部门数据列表
      getDepartList () {
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsorganizationinfo/select'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000,
            'key': '',
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            if(data.menuList&&data.menuList.length>0){
              data.menuList.forEach(ele=>{
                if(ele.organizationId==-1){
                  ele.disabled = true;
                }
              })
            }
            this.orgList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
          } else {
            this.orgList = []
          }
        })
      },
      changeAddedVal(){
        this.dataForm.addedValList = [];
        let len = 12;
        if(this.dataForm.quotaUnit==3){
          len =24;
        }else if(this.dataForm.quotaUnit==4){
          len =31;
        }
        else{
          len =12;
        }
        for(let i=0;i<len;i++){
          let date = 0;
          if(this.dataForm.quotaUnit==3){
            if(i<10){
                date = '0'+i;
            }
            else{
              date =i;
            }
          }
          else{
            if(i<9){
               date = '0'+(i+1);
            }
            else{
              date =(i+1);
            }
          }
          this.dataForm.addedValList.push({
            timePoint:date,
            val:0
          })
        }
      },
      //获取设备列表
      getDeviceDataList(){
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsmeterinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 1000000,
            "projectid":this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.deviceList = data.page.list
          } else {
            this.deviceList = []
          }
        })
      },
      closeDialog(){
        this.showTree = false;
      },
      selectDepart(){
        this.dataForm.departName=''
        this.dataForm.meterCode= [];
        if(this.dataForm.quotaOType==2){
          let build = this.$refs.buildTree.getCheckedNodes();
          if(build.length>0){
            build.forEach((ele,index)=>{
              this.dataForm.meterCode.push(ele.buildingId);
              this.dataForm.departName+=ele.buildingName;
              if(index<build.length-1){
                 this.dataForm.departName+=",";
              }
            })
          }
        }
        else if(this.dataForm.quotaOType==3){
           let build = this.$refs.departTree.getCheckedNodes();
           if(build.length>0){
            build.forEach((ele,index)=>{
              this.dataForm.meterCode.push(ele.organizationId);
              this.dataForm.departName+=ele.organizationName;
              if(index<build.length-1){
                  this.dataForm.departName+=",";
              }
            })
          }
        }
        this.showTree = false;
      },
      changeQuotaOType(){
        if(this.dataForm.quotaOType==this.oldDevice.oldQuotaOType){
          this.dataForm.meterCode = this.oldDevice.ids;
          this.dataForm.departName= this.oldDevice.name;
        }else{
          this.dataForm.meterCode = [];
          this.dataForm.departName="";
        }
        if(this.dataForm.quotaOType!==1){
          this.querySubitem('')
        }
      },
      changeQuotaUnit(){
        if(this.dataForm.quotaType==1){
          if(this.dataForm.quotaUnit==1){
            this.dataForm.quotaUnit=2;
          }
        }else{
          this.dataForm.quotaUnit = this.oldDevice.oldQuotaUnit;
        }
      },
      inputDevice(){
        this.showTree = true;
        this.$nextTick(()=>{
          if(this.dataForm.quotaOType==3){
            this.$refs.departTree.setCheckedKeys(this.dataForm.meterCode);
          }
          else if(this.dataForm.quotaOType==2){
            this.$refs.buildTree.setCheckedKeys(this.dataForm.meterCode);
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsquotainfo/${!this.dataForm.quotaId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'quotaId': this.dataForm.quotaId || undefined,
                'quotaName': this.dataForm.quotaName,
                'quotaType': this.dataForm.quotaType,
                'upVal': this.dataForm.upVal,
                'downVal': this.dataForm.downVal,
                'quotaCycle': this.dataForm.quotaCycle,
                'quotaOType': this.dataForm.quotaOType,
              //  'addedVal': this.dataForm.addedVal,
                'quotaUnit': this.dataForm.quotaUnit,
                'notes': this.dataForm.notes,
                'collectType':this.dataForm.collectType,
                objectId:this.dataForm.meterCode,
                customerId: this.$util.cookies.get("customer_id"),
                timeVals:this.dataForm.addedValList
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      changeMeter(){

       let meterType =this.dataForm.meterCode.length>0? this.deviceList.find(item=>item.meterCode==this.dataForm.meterCode[0]).meterType:'';
          this.querySubitem(meterType)
      },
      querySubitem(meterType){
        //查询子分类
        this.queryCollectType(meterType,this.dataForm.quotaType,data=>{
          if (data && data.code === 0) {
          this.meterTypeParamValueList = data.page.list
        } else {
          this.meterTypeParamValueList = [];
        }
      });
      },
      /**
       * 获取采集分项
       */
      queryCollectType(type,paramValue,callback) {
        let params = {
          'meterType': type ,
          'state': '1' ,
          'cumulativeType':paramValue,
          "customerId":this.$util.cookies.get('customer_id'),
          'page': 1,
          'limit': 10000,
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
    },
  }
</script>
<style>
 .input-with-select .el-input-group__append {
    background-color: #fff;
    width: 80px;
  }
</style>
<style scoped lang="scss">
  /*@import "../../../assets/scss/_variables";*/
  .objectTree {
      position: absolute;
      overflow: auto;
      z-index: 100;
      height: 200px;
      /* border: 1px solid #ddd; */
      line-height: normal;
      z-index: 204;
      box-shadow: 0px 0px 1px 1px #e2dfdf;
      margin-top: 3px;
      border-radius: 4px;
    background-color: white;
  }
</style>
